import pytz
from django.db import models

from social.account.models import User
from social.utils.models import BaseModel


class Rank(BaseModel):
    key = models.CharField(max_length=50)

    user = models.ForeignKey(User, related_name='ranks', on_delete=models.CASCADE)

    coin = models.IntegerField(default=0)

    class Meta:
        unique_together = [
            'key', 'user'
        ]
        index_together = [
            ('key', 'coin')
        ]

    @classmethod
    def key_day_in(cls, date):
        date_tz = date.astimezone(pytz.timezone('Asia/Shanghai'))
        d = date_tz.strftime('%Y-%m-%d')
        return f'key_day_in_{d}'

    @classmethod
    def key_day_out(cls, date):
        date_tz = date.astimezone(pytz.timezone('Asia/Shanghai'))
        d = date_tz.strftime('%Y-%m-%d')
        return f'key_day_out_{d}'

    @classmethod
    def key_week_in(cls, date):
        date_tz = date.astimezone(pytz.timezone('Asia/Shanghai'))
        cal = date_tz.isocalendar()
        return f"week_in_{cal[0]}-{cal[1]}"

    @classmethod
    def key_week_out(cls, date):
        date_tz = date.astimezone(pytz.timezone('Asia/Shanghai'))
        cal = date_tz.isocalendar()
        return f"week_out_{cal[0]}-{cal[1]}"

    @classmethod
    def key_month_in(cls, date):
        date_tz = date.astimezone(pytz.timezone('Asia/Shanghai'))
        m = date_tz.strftime('%Y-%m')
        return f'key_month_in_{m}'

    @classmethod
    def key_month_out(cls, date):
        date_tz = date.astimezone(pytz.timezone('Asia/Shanghai'))
        m = date_tz.strftime('%Y-%m')
        return f'key_month_out_{m}'
